package com.jckl.foodathon.services.location;

import org.restlet.ext.jackson.JacksonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

import android.app.Activity;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.jckl.foodathon.R;
import com.jckl.foodathon.activities.HomeActivity;
import com.jckl.foodathon.common.constant.CommunicationConstants;
import com.jckl.foodathon.model.Coordinate;

public class LocalityQuery {
	
	public void getLocality(Activity activity, View view, double latitude, double longitude){
		
		Coordinate coordinate = new Coordinate(latitude, longitude);
			
		PerformLocalityQueryAsync async = new PerformLocalityQueryAsync(activity, view, coordinate);
		async.execute();
		
	}
	
	private class PerformLocalityQueryAsync extends AsyncTask<Void, Void, Boolean> {
	
		Activity activity;
		Coordinate coordinate;
		TextView my_locality;
		String locality = "";
		
		public PerformLocalityQueryAsync(Activity activity, View view, Coordinate coordinate) {
			this.activity = activity;
			this.coordinate = coordinate;
			this.my_locality = (TextView) view.findViewById(R.id.my_locality);
		}
		
		@Override
		protected void onPreExecute() {
			
		}
		
		@Override
		protected Boolean doInBackground(Void... nothing) {
		
			boolean localityQuerySuccess = false;
			
			try{
				ClientResource cr = new ClientResource(CommunicationConstants.SERVER_URI+CommunicationConstants.GEO_CODING);
				JacksonRepresentation<Coordinate> coord = new JacksonRepresentation<Coordinate>(coordinate);
				Representation rep = cr.put(coord);
				locality = rep.getText();
				localityQuerySuccess = true;
				
			} catch (Exception ex){
				Log.e(CommunicationConstants.APP_TAG, "Unable to get locality info");
				ex.printStackTrace();
			}
			
			return localityQuerySuccess;
		}
		
		@Override
		protected void onProgressUpdate(Void... nothing){
			
	    }
		
		@Override
		protected void onPostExecute(Boolean successExecution) {
			if(successExecution){
				this.my_locality.setText(locality);
				//update the locality into activity's coordinate
				Coordinate coordinate = ((HomeActivity)activity).getCoordinate();
				coordinate.setLocality(locality);
				((HomeActivity)activity).setCoordinate(coordinate);
			}else{
				Toast.makeText(activity.getApplicationContext(), "Location Query Failed", Toast.LENGTH_SHORT).show();
			}
			
		}
	}

}
